package com.originskyseed.platform.job.jobhandler.count;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import com.originskyseed.platform.core.job.biz.model.ReturnT;
import com.originskyseed.platform.core.job.handler.IJobHandler;
import com.originskyseed.platform.core.job.handler.annotation.JobHandler;
import com.originskyseed.platform.core.job.log.JobLogger;
import com.originskyseed.platform.count.service.IUserRechargeService;
import com.originskyseed.platform.user.service.IUserInfoService;

/**
 * 员工每日充值定时任务
 * 
 * @Author: twh @date: 2021/6/4
 */

@Component
@JobHandler(value = "staffRechargeDailyHandler")
public class StaffRechargeDailyHandler extends IJobHandler {

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private IUserRechargeService userRechargeService;

	@Override
	public ReturnT<String> execute(String tenantCode) throws Exception {
		try {
			// 获取开始统计的时间
			List<String> params = Arrays.asList(tenantCode.split(","));
			// 如果有传参则根据传递的参数查询，没有则根据当前日期查询
			String time = null;
			SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
			if (params.size() > 1) {
				time = params.get(1);
				tenantCode = params.get(0);
			} else {
				time = sim.format(new Date());
			}
			this.userRechargeService.insertsUserRechargeByTime(time, tenantCode);

		} catch (Exception e) {
			JobLogger.log("统计员工每日充值数据：" + getExceptionDetail(e));
			return FAIL;
		}
		return SUCCESS;
	}

	/**
	 * 返回两个时间间隔内的所有日期
	 * 
	 * @param dateStart
	 * @param dateEnd
	 * @return
	 */
	/*
	 * public static List<String> getTwoDaysDay(String dateStart, String dateEnd) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); List<String> dateList = new ArrayList<String>(); try { Date dateOne = sdf.parse(dateStart); Date dateTwo = sdf.parse(dateEnd); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateOne); dateList.add(sdf.format(dateOne)); while
	 * (calendar.getTime().before(dateTwo)) { calendar.add(Calendar.DAY_OF_MONTH, +1); dateList.add(sdf.format(calendar.getTime())); } } catch (Exception e) { e.printStackTrace(); } return dateList; }
	 */

	/**
	 * 获取异常详细信息，知道出了什么错，错在哪个类的第几行 .
	 *
	 * @param ex
	 * @return
	 */
	public static String getExceptionDetail(Exception ex) {
		String ret = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		PrintStream pout = new PrintStream(out);
		try {
			ex.printStackTrace(pout);
			ret = new String(out.toByteArray());
		} catch (Exception e) {
		} finally {
			try {
				pout.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

}
